<template>
  <div class="task-detail" v-loading="loading">
    <h1>任务详情</h1>
    <el-card v-if="task">
      <template #header>
        <div class="card-header">
          <span>任务信息</span>
          <div>
            <el-button 
              type="success" 
              @click="startTask"
              :disabled="task.status !== 'CREATED' && task.status !== 'PAUSED'"
            >
              启动
            </el-button>
            <el-button 
              type="warning" 
              @click="pauseTask"
              :disabled="task.status !== 'RUNNING'"
            >
              暂停
            </el-button>
            <el-button 
              v-if="task.status === 'FAILED' && runtime && runtime.last_error"
              type="info" 
              @click="showErrorDialog = true"
            >
              查看错误详情
            </el-button>
          </div>
        </div>
      </template>
      <div>
        <p><strong>任务名称:</strong> {{ task.name }}</p>
        <p><strong>任务类型:</strong> {{ task.type }}</p>
        <p><strong>状态:</strong> 
          <el-tag :type="getStatusTagType(task.status)">{{ task.status }}</el-tag>
        </p>
        <p><strong>创建时间:</strong> {{ task.created_at }}</p>
      </div>
    </el-card>
    
    <el-card v-if="runtime">
      <template #header>
        <span>监控信息</span>
      </template>
      <div>
        <p><strong>延迟:</strong> {{ runtime.delay_seconds }} 秒</p>
        <p><strong>QPS:</strong> {{ runtime.qps }}</p>
        <p><strong>最后错误:</strong> <span :class="{'error-message': runtime.last_error}">{{ runtime.last_error || '无' }}</span></p>
        
        <!-- 进度条 -->
        <div v-if="task && (task.status === 'RUNNING' || task.status === 'COMPLETED' || task.status === 'FAILED')" class="progress-section">
          <p><strong>任务进度:</strong></p>
          <el-progress 
            :percentage="progressPercentage" 
            :status="progressStatus"
          />
          <p class="progress-text">{{ progressText }}</p>
        </div>
      </div>
    </el-card>
    
    <el-card v-if="task">
      <template #header>
        <span>源数据库配置</span>
      </template>
      <div>
        <p><strong>类型:</strong> {{ task.source.type }}</p>
        <p><strong>主机:</strong> {{ task.source.host }}:{{ task.source.port }}</p>
        <p><strong>用户名:</strong> {{ task.source.user }}</p>
        <p><strong>数据库:</strong> {{ task.source.database }}</p>
        <!-- 显示迁移映射信息 -->
        <div v-if="isBatchTask" class="mapping-info">
          <p><strong>迁移映射:</strong> {{ getMappingInfo() }}</p>
        </div>
      </div>
    </el-card>
    
    <el-card v-if="task">
      <template #header>
        <span>目标数据库配置</span>
      </template>
      <div>
        <p><strong>类型:</strong> {{ task.target.type }}</p>
        <p><strong>主机:</strong> {{ task.target.host }}:{{ task.target.port }}</p>
        <p><strong>用户名:</strong> {{ task.target.user }}</p>
        <p><strong>数据库:</strong> {{ task.target.database }}</p>
      </div>
    </el-card>
    
    <el-button @click="goBack">返回</el-button>
    
    <!-- 错误详情对话框 -->
    <el-dialog v-model="showErrorDialog" title="错误详情" width="50%">
      <el-alert
        v-if="runtime && runtime.last_error"
        :title="runtime.last_error"
        type="error"
        show-icon
        closable
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showErrorDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      show-icon
      closable
      @close="clearError"
    />
    
    <el-alert
      v-if="successMessage"
      :title="successMessage"
      type="success"
      show-icon
      closable
      @close="clearSuccessMessage"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTaskStore } from '@/stores/task'

const route = useRoute()
const router = useRouter()
const taskStore = useTaskStore()

const task = ref(null) as any
const runtime = ref(null) as any
const loading = ref(false)
const error = ref(null)
const successMessage = ref(null)
const showErrorDialog = ref(false)

// WebSocket连接
const websocket = ref<WebSocket | null>(null)
const websocketUrl = `ws://localhost:8000/api/v1/ws/task/${route.params.id}`

// 进度相关状态
const progressPercentage = ref(0)
const progressText = ref('准备中...')

// 轮询定时器
let pollingTimer: any = null
let progressTimer: any = null

// 计算进度条状态
const progressStatus = computed(() => {
  if (task.value) {
    if (task.value.status === 'COMPLETED') {
      return 'success'
    } else if (task.value.status === 'FAILED') {
      return 'exception'
    }
  }
  return null
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'RUNNING':
      return 'primary'
    case 'COMPLETED':
      return 'success'
    case 'FAILED':
      return 'danger'
    case 'PAUSED':
      return 'warning'
    default:
      return 'info'
  }
}

// 监听任务状态变化，更新进度
watch(() => task.value?.status, (newStatus, oldStatus) => {
  if (newStatus === 'RUNNING') {
    startProgressTracking()
  } else if (newStatus === 'COMPLETED') {
    stopProgressTracking()
    progressPercentage.value = 100
    progressText.value = '任务已完成'
    stopPolling()
  } else if (newStatus === 'FAILED') {
    stopProgressTracking()
    progressPercentage.value = 0
    progressText.value = '任务执行失败'
    stopPolling()
  }
})

// 启动任务
const startTask = async () => {
  try {
    const result = await taskStore.startTask(route.params.id as string)
    successMessage.value = result.message
    // 重新获取任务详情
    await loadTaskDetail()
  } catch (err: any) {
    error.value = err.message || '启动任务失败'
  }
}

// 暂停任务
const pauseTask = async () => {
  try {
    const result = await taskStore.pauseTask(route.params.id as string)
    successMessage.value = result.message
    // 重新获取任务详情
    await loadTaskDetail()
  } catch (err: any) {
    error.value = err.message || '暂停任务失败'
  }
}

// 加载任务详情
const loadTaskDetail = async () => {
  try {
    loading.value = true
    const taskDetail = await taskStore.fetchTaskDetail(route.params.id as string)
    task.value = taskDetail
    
    // 获取运行时信息
    if (taskDetail.id) {
      const runtimeData = await taskStore.fetchTaskStatus(taskDetail.id)
      runtime.value = runtimeData
    }
  } catch (err: any) {
    error.value = err.message || '获取任务详情失败'
  } finally {
    loading.value = false
  }
}

// 初始化WebSocket连接
const initWebSocket = () => {
  try {
    // 先关闭已有的连接
    if (websocket.value) {
      websocket.value.close()
    }
    
    // 创建新的WebSocket连接
    websocket.value = new WebSocket(websocketUrl)
    
    websocket.value.onopen = () => {
      console.log('WebSocket连接已建立')
    }
    
    websocket.value.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        if (data.type === 'status_update') {
          // 更新任务状态
          if (task.value) {
            task.value.status = data.status
          }
          // 显示消息
          if (data.message) {
            successMessage.value = data.message
          }
          // 重新加载任务详情
          loadTaskDetail()
        }
      } catch (e) {
        console.error('解析WebSocket消息失败:', e)
      }
    }
    
    websocket.value.onerror = (error) => {
      console.error('WebSocket错误:', error)
    }
    
    websocket.value.onclose = () => {
      console.log('WebSocket连接已关闭')
    }
  } catch (e) {
    console.error('初始化WebSocket连接失败:', e)
  }
}

// 开始进度跟踪
const startProgressTracking = () => {
  // 模拟进度增加
  progressTimer = setInterval(() => {
    if (progressPercentage.value < 90) {  // 最多到90%，完成由后端通知
      progressPercentage.value += Math.random() * 5
      progressText.value = `正在执行中... (${Math.round(progressPercentage.value)}%)`
    }
  }, 1000)
}

// 停止进度跟踪
const stopProgressTracking = () => {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
}

// 开始轮询
const startPolling = () => {
  stopPolling() // 先停止已有的轮询
  pollingTimer = setInterval(() => {
    loadTaskDetail()
  }, 5000) // 每5秒轮询一次
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
  }
}

// 清除错误
const clearError = () => {
  error.value = null
}

// 清除成功消息
const clearSuccessMessage = () => {
  successMessage.value = null
}

// 返回
const goBack = () => {
  router.back()
}

// 判断是否为批量任务
const isBatchTask = computed(() => {
  return task.value && task.value.name.includes(' - ') && task.value.name.includes(' → ')
})

// 获取迁移映射信息
const getMappingInfo = () => {
  if (!task.value || !isBatchTask.value) return ''
  
  // 从任务名称中提取映射信息
  const parts = task.value.name.split(' - ')
  if (parts.length > 1) {
    return parts[1] // 返回 "源数据库 → 目标数据库" 部分
  }
  return ''
}

// 组件挂载时
onMounted(async () => {
  await loadTaskDetail()
  initWebSocket()
  startPolling()
})

// 组件卸载时
onUnmounted(() => {
  // 关闭WebSocket连接
  if (websocket.value) {
    websocket.value.close()
  }
  // 停止轮询
  stopPolling()
  // 停止进度跟踪
  stopProgressTracking()
})
</script>

<style scoped>
.task-detail {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card {
  margin-bottom: 20px;
}

.progress-section {
  margin-top: 20px;
}

.progress-text {
  margin-top: 10px;
  text-align: center;
  color: #666;
}

.error-message {
  color: #f56c6c;
  font-weight: bold;
}

.dialog-footer {
  text-align: right;
}

.mapping-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.mapping-info strong {
  color: #409eff;
}
</style>